package com.mego.weblink.activitys;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.DhcpInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;

import com.mego.weblink.R;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.ui.EditTextInfoActivity;
import zuo.biao.library.ui.EditTextInfoWindow;
import zuo.biao.library.util.StringUtil;

public class TaizhuActivity extends BaseActivity implements View.OnClickListener {


    public static final int INITFINISH = 1101;
    private final String TAG = "TaizhuActivity";

    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    private final int REQUEST_TO_DOPAY = 25;
    public static final int FINISHSEND = 607;
    private final int REFRESHLIST = 26;

    ProgressDialog mPB;
    String _rmsg = "";//返回的消息

    private ScrollView svDemoMain;
    private TextView tv_name;
    private TextView tv_mima;
    private TextView tv_jtname;
    private TextView tv_wifiinfo;
    private TextView tv_jtinfo;
    private long firstTime = 0;//第一次返回按钮计时

    public static Intent createIntent(Context context) {
        return new Intent(context, TaizhuActivity.class);
    }

    @Override
    public Activity getActivity() {
        return this;
    }
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == INITFINISH) {
                if (mPB != null) {
                    mPB.dismiss();
                    mPB = null;
                }
            } else if (msg.what == REFRESHLIST) {
                //已tcp发送给设备
                showShortToast("已经复制deviceid: " + _rmsg);

                //获取剪贴板管理器：
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label", _rmsg);
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);

                tv_jtinfo.setText("机台deviceid：\n" + _rmsg);
            } else if (msg.what == FINISHSEND) {
                showShortToast("已经发送！");
            }
        }
    };
    private ConnectThread ct = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.taizhu_activity);

        initView();
        initData();
        initEvent();

//        onReset();
//        onLink();
    }

    @Override
    public void initData() {


    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    void onReset() {
        if (ct != null) {
            ct.interrupt();
            ct = null;
        }
        ct = new ConnectThread();
        ct.start();
    }

    @Override
    public void onForwardClick(View v) {

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                break;
//            case KeyEvent.KEYCODE_BACK:
//                onExit();
//                return true;
        }

        return super.onKeyUp(keyCode, event);
    }

    void onExit() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            showShortToast(getString(R.string.texit));
            firstTime = secondTime;
        } else {//完全退出
            moveTaskToBack(false);//应用退到后台
            System.exit(0);
        }

    }

    private final int REQUEST_TO_EDIT_NAME = 33;
    private final int REQUEST_TO_EDIT_MIMA = 34;
    private final int REQUEST_TO_EDIT_JTNAME = 35;

    @Override
    public void initView() {
        svDemoMain = (ScrollView) findViewById(R.id.svDemoMain);

        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_mima = (TextView) findViewById(R.id.tv_mima);
        tv_jtname = (TextView) findViewById(R.id.tv_jtname);
        tv_wifiinfo = (TextView) findViewById(R.id.tv_wifiinfo);
        tv_jtinfo = (TextView) findViewById(R.id.tv_jtinfo);;

    }

    private void editName(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NAME
                    , getString(R.string.wifiname), StringUtil.getTrimedString(tv_name), getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NAME
                    , getString(R.string.wifiname), StringUtil.getTrimedString(tv_name));
        }

        toActivity(intent, REQUEST_TO_EDIT_NAME, !toWindow);
    }

    @Override
    public void initEvent() {
        findViewById(R.id.detail_1).setOnClickListener(this);
        findViewById(R.id.detail_2).setOnClickListener(this);
        findViewById(R.id.detail_3).setOnClickListener(this);

        findViewById(R.id.bt_link).setOnClickListener(this);
        findViewById(R.id.bt_send).setOnClickListener(this);
        findViewById(R.id.bt_bind).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.detail_1:
                editName(true);
                break;
            case R.id.detail_2:
                editMima(true);
                break;
            case R.id.detail_3:
                editJtname(true);
                break;
            case R.id.bt_link:
                onLink();
                break;
            case R.id.bt_send:
                onSend();
                break;
            case R.id.bt_bind:
                onBind();
                break;
        }
    }

    private void editMima(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NAME
                    , getString(R.string.wifimima), StringUtil.getTrimedString(tv_mima), getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NAME
                    , getString(R.string.wifimima), StringUtil.getTrimedString(tv_mima));
        }

        toActivity(intent, REQUEST_TO_EDIT_MIMA, !toWindow);
    }

    private void editJtname(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NAME
                    , getString(R.string.jtname), StringUtil.getTrimedString(tv_jtname), getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NAME
                    , getString(R.string.jtname), StringUtil.getTrimedString(tv_jtname));
        }

        toActivity(intent, REQUEST_TO_EDIT_JTNAME, !toWindow);
    }

    WifiManager mWifiManager;

    private WifiInfo wifiInfo;
    private DhcpInfo dhcpInfo;

    private void onBind() {

    }

    private String intToIp(int paramInt) {
        return (paramInt & 0xFF) + "." + (0xFF & paramInt >> 8) + "." + (0xFF & paramInt >> 16) + "."
                + (0xFF & paramInt >> 24);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        switch (requestCode) {
            case REQUEST_TO_DOPAY:
                break;
            case REQUEST_TO_EDIT_NAME:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    tv_name.setText(name);
                }
                break;
            case REQUEST_TO_EDIT_MIMA:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    tv_mima.setText(name);
                }
                break;
            case REQUEST_TO_EDIT_JTNAME:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    tv_jtname.setText(name);
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void onSend() {

        String SSID = tv_name.getText().toString();
        String PSW = tv_mima.getText().toString();
//        final String msg = "AT+CWJAP=" + SSID + "," + PSW;
//        ”SSID”,”PWD”
        final String msg = String.format("AT+CWJAP=\"%s\",\"%s\"", SSID, PSW);

        new Thread(new Runnable() {
            @Override
            public void run() {

                //发送数据
                try {
                    if (ct != null) {
                        ct.outputStream.write(msg.getBytes());
                        mHandler.sendEmptyMessage(FINISHSEND);
                    }

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }).start();

    }

    private void onLink() {

        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        dhcpInfo = mWifiManager.getDhcpInfo();
        wifiInfo = mWifiManager.getConnectionInfo();

        StringBuilder sb = new StringBuilder();
        sb.append("\n机台WIFI信息：");
//        sb.append("\nipAddress：" + intToIp(dhcpInfo.ipAddress));
//        sb.append("\nnetmask：" + intToIp(dhcpInfo.netmask));
        sb.append("\ngateway：" + intToIp(dhcpInfo.gateway));//网关ip 192.168.31.1
//        sb.append("\nserverAddress：" + intToIp(dhcpInfo.serverAddress));
//        sb.append("\ndns1：" + intToIp(dhcpInfo.dns1));
//        sb.append("\ndns2：" + intToIp(dhcpInfo.dns2));
        sb.append("\n");

//        sb.append("Wifi信息：");
//        sb.append("\nIpAddress：" + intToIp(wifiInfo.getIpAddress()));
//        sb.append("\nMacAddress：" + wifiInfo.getMacAddress());

//        tv_wifiinfo.setText(sb);
        tv_wifiinfo.setText("机台网关：" + intToIp(dhcpInfo.gateway));

        if (intToIp(dhcpInfo.gateway).compareToIgnoreCase("192.168.4.1") != 0) {
            showShortToast("机台网关错误，请手动连接机台的WIFI。");
        } else {
            showShortToast("已连接机台的WIFI。");
            onReset();//连tcp
        }

    }

    class ConnectThread extends Thread {
        public Socket socket = null;        //定义socket
        public OutputStream outputStream = null;    //定义输出流（发送）
        public InputStream inputStream = null;    //定义输入流（接收）

        public void run() {
            socket = null;
            try {
                socket = new Socket("192.168.4.1", 8080);
//                socket = new Socket("192.168.31.139", 8902);//本机

            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (socket == null) {
                return;
            }

            //获取输出流
            try {
                outputStream = socket.getOutputStream();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                while (true) {
                    final byte[] buffer = new byte[1024];//创建接收缓冲区
                    if (socket.isClosed()) {
                        return;
                    }
                    inputStream = socket.getInputStream();
                    final int len = inputStream.read(buffer);//数据读出来，并且返回数据的长度

                    _rmsg = new String(buffer,"UTF-8");

                    runOnUiThread(new Runnable()//不允许其他线程直接操作组件，用提供的此方法可以
                    {
                        public void run() {
                            mHandler.sendEmptyMessage(REFRESHLIST);
                        }
                    });
                }
            } catch (IOException e) {

            }

        }
    }

}

